package org.urey.udp;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

public class UdpActivity extends Activity {
 
	private static final String IP = "ip";
	private static final String PORT = "port";
	private static final String TXT = "txt";

	private EditText et_ip;
	private EditText et_port;
	private EditText et_txt;
	private Button send;

	private TextView result;

	private ScrollView scrollView;

	private Runnable runnable;

	DatagramSocket client;

	private boolean flag = false;

	Editor editor;

	SharedPreferences sp;

	@SuppressLint("HandlerLeak")
	Handler activityHandler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == 1) {
				result.append("\n收到:" + msg.obj.toString());
				scrollView.post(runnable);
			} else if (msg.what == 2) {
				result.append("\n错误:" + ((Exception) msg.obj).getMessage());
				scrollView.post(runnable);
			}
		}
	};

	public String getLocalMacAddress() {
		WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		WifiInfo info = wifi.getConnectionInfo();
		return info.getMacAddress();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home);

		sp = getSharedPreferences("SP", MODE_PRIVATE);
		editor = sp.edit();

		et_ip = (EditText) findViewById(R.id.edit_ip);
		et_port = (EditText) findViewById(R.id.edit_port);
		et_txt = (EditText) findViewById(R.id.edit_txt);
		result = (TextView) findViewById(R.id.text_result);
		send = (Button) findViewById(R.id.button_form);
		scrollView = (ScrollView) findViewById(R.id.sv);

		runnable = new Runnable() {
			public void run() {
				scrollView.fullScroll(ScrollView.FOCUS_DOWN);
				send.requestFocus();
			}
		};
		try {
			client = new DatagramSocket();
			new Thread() {
				public void run() {
					while (true) {
						try {
							byte[] recvBuf = new byte[548];
							DatagramPacket recvPacket = new DatagramPacket(recvBuf, recvBuf.length);
							client.receive(recvPacket);
							String recvStr = new String(recvPacket.getData(), 0, recvPacket.getLength());
							Message m = new Message();
							m.what = 1;
							m.obj = recvStr;
							activityHandler.sendMessage(m);
						} catch (Exception e) {
							Message m = new Message();
							m.what = 2;
							m.obj = e;
							activityHandler.sendMessage(m);
						}
					}
				}
			}.start();
		} catch (Exception e) {
			e.printStackTrace();
			toast(e.getMessage());
		}

		init();
	}

	private void toast(String s) {
		Toast.makeText(UdpActivity.this, s, Toast.LENGTH_LONG).show();
	}

	private void init() {
		et_ip.setText(sp.getString(IP, "192.168.1.101"));
		et_port.setText(sp.getString(PORT, "8099"));
		et_txt.setText(sp.getString(TXT, "1"));
		result.setText("reslut");

		send.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				synchronized (et_ip) {
					if (flag) {
						return;
					}
					flag = true;
				}
				try {
					String ip = et_ip.getText().toString();
					String portStr = et_port.getText().toString();
					String txt = et_txt.getText().toString();

					editor.putString(IP, ip);
					editor.putString(PORT, portStr);
					editor.putString(TXT, txt);
					editor.commit();

					InetAddress addr = InetAddress.getByName(ip);
					result.append("\n发送:" + txt);
					scrollView.post(runnable);

					byte[] b = txt.getBytes("UTF-8");

					int port = Integer.valueOf(portStr);
					DatagramPacket sendPacket = new DatagramPacket(b, b.length, addr, port);
					client.send(sendPacket);
				} catch (Exception e) {
					e.printStackTrace();
					toast(e.getMessage());
				}
				flag = false;
			}
		});
	}
}
